const {
	Service
} = require('uni-cloud-router');
const {
	pageFundBaseList
} = require('lg-request-fund');
const {
	confMap
} = require("lg-constant");
const {
	parser,
	success,
	exception,
	error,
	typeOf,
} = require("lg-utils");
const db = uniCloud.database();
const dbCmd = db.command;
const fundColl = db.collection("fund-base");
const logTimingColl = db.collection("log-timing");
const dataDictionaryColl = db.collection("data-dictionary");
module.exports = class FundService extends Service {
	async fetchFundListTotal() {
		try {

			const {
				data: {
					result: {
						data: {
							totalnum = 0
						} = {}
					} = {},
				} = {},
				status = ""
			} = await pageFundBaseList() || {};
			if (confMap.get("success") === status && totalnum) {
				return totalnum;
			}

		} catch (e) {
			throw e
		}
	}
	// 插入基金基本信息
	async addFundBaseList({
		pageSize = 5000
	} = {}) {
		let insertedCount = 0;
		const count = await this.fetchFundListTotal();
		if (count) {
			const countInt = Number.parseInt(count);
			const pageCount = Math.ceil(countInt / pageSize);
			for (let i = 1; i <= pageCount; i++) {
				try {
					const {
						data: {
							result: {
								data: {
									data: list = []
								} = {}
							} = {},
						} = {},
						status = ""
					} = await pageFundBaseList({
						page: i,
						num: pageSize
					}) || {};
					if (confMap.get("success") === status) {
						if (list && list.length) {
							try {
								const {
									inserted
								} = await fundColl.add(list) || {};
								if (inserted) {
									insertedCount += inserted;
								}
								console.log(pageCount, ">", i, ">", inserted);
							} catch (e) {
								return error("数据库插入列表异常", {
									index: i,
									err: e
								});
							}
						}
					} else {
						return error("请求远程分页数据异常", {
							index: i,
							err: status
						})
					}

				} catch (e) {
					return error("循环插入捕获数据列表异常", {
						index: i,
						err: e
					});
				}
			}
			return success(count);
		} else {
			return error("捕获基金基础信息列表总条目数异常.", count);
		}

	}
	// 获取symbol 集合
	async getFundSymbolList() {
		try {
			const pageSize = 500;
			const {
				affectedDocs,
				total
			} = await fundColl.count();
			if (total) {
				const pageCount = Math.ceil(total / pageSize);
				const symbolList = [];
				for (let i = 0; i < pageCount; i++) {
					const {
						affectedDocs,
						data: list
					} = await fundColl.skip(i * pageSize).limit(pageSize).get() || {};
					if (affectedDocs) {
						const mapList = list.map(mi => mi.symbol);
						symbolList.push(...mapList);
						console.log(pageCount, ">", i + 1);
					}
				}
				return symbolList;

			} else {
				return 0;
			}

		} catch (e) {
			return 0;
		}
	}
	// 更新基金symbol 集合; 
	async updateFundSymbolList() {
		try {
			const symbolList = await this.getFundSymbolList();
			if (symbolList) {
				try {

					const {
						affectedDocs,
						updated
					} = await dataDictionaryColl.where({
						type: "fundSymbolList"
					}).update({
						data: symbolList
					}) || {};

					return success(`成功更新的数据项:${updated}`)
				} catch (e) {
					throw e
				}
			} else {
				return error("获取symbol集合异常", symbolList);
			}
		} catch (e) {
			throw e
		}
	}
	// 新增基金symbol 集合; 
	async addFundSymbolList() {
		try {
			const symbolList = await this.getFundSymbolList();
			console.log(symbolList);
			if (symbolList) {
				return await dataDictionaryColl.add({
					type: "fundSymbolList",
					name: "基金symbol集合",
					subjectCode: "fund",
					subjectName: "基金",
					data: symbolList
				});
			} else {
				return error("获取symbol集合异常", symbolList);
			}
		} catch (e) {
			throw e
		}
	}

	// 更新基金基本信息
	async updateFundBaseList({
		pageSize = 10
	} = {}) {

		try {
			let updateCount = 0;
			let newFundModelList = [];
			const count = await this.fetchFundListTotal();
			const {
				affectedDocs: dicDocs,
				data: {
					0: {
						data: symbollist
					} = {}
				} = []
			} =
			await dataDictionaryColl.where({
				type: "fundSymbolList"
			}).get() || {};
			if (count && dicDocs) {
				const countInt = Number.parseInt(count);
				const pageCount = Math.ceil(countInt / pageSize);
				for (let i = 1; i <= pageCount; i++) {
					try {
						const {
							data: {
								result: {
									data: {
										data: list = []
									} = {}
								} = {},
							} = {},
							status = ""
						} = await pageFundBaseList({
							page: i,
							num: pageSize
						}) || {};
						if (confMap.get("success") === status) {
							if (list && list.length) {
								const promises = [];
								for (let [listIndex, listValue] of Object.entries(list)) {
									const {
										symbol = ""
									} = listValue || {};
									if (symbollist.includes(symbol)) {
										//已有数据就更新
										promises.push(fundColl.where({
											symbol
										}).update(listValue));
									} else {
										// 新的添加
										newFundModelList.push(listValue);
									}

								}
								try {

									const execPromiseAllResults = await Promise.all(promises) || [];
									console.log(pageCount, ">", i);
									const partUpdateList = execPromiseAllResults.filter(({
										affectedDocs,
										updated
									} = {}) => {
										return updated === 1
									})
									if (partUpdateList && partUpdateList.length) {
										const partUpdateCount = partUpdateList.length || 0;
										updateCount += partUpdateCount;
									}
								} catch (e) {
									return error("更新数据请求异常.", {
										index: i,
										err: e
									})
								}
							}

							// 更新基金列表 
							if (newFundModelList && newFundModelList.length) {
								try {
									const {
										affectedDocs
									} = await fundColl.add(newFundModelList);
									if (affectedDocs) {
										const newSymbolList = newFundModelList.map(ni => ni.symbol)
										try {
											await dataDictionaryColl.where({
												type: "fundSymbolList"
											}).update({
												data: dbCmd.push(newSymbolList)
											});

										} catch (e) {
											return error("更新基金symbo集合异常;",e);
										}
									}
								} catch (e) {
									return error("插入新基金数据异常;", e);
								}

							}
						} else {
							return error("请求远程分页数据异常;", {
								index: i,
								err: status
							})
						}

					} catch (e) {
						return error("循环更新捕获数据列表异常", {
							index: i,
							err: e
						});
					}
				}
				return success(updateCount);
			} else {
				return error("捕获基金基础信息列表总条目数异常.", count);
			}
		} catch (e) {
			throw e
		}

	}

	async removeFundBaseList() {
		try {
			return await fundColl.where({
				_id: dbCmd.exists(true)
			}).remove();
		} catch (e) {
			throw e;
		}
	}

}
